import React, { Component } from 'react';
import {
    NavBar,
    Toast,
    WhiteSpace,
    Card,
    Flex,
    List,
    Modal,
    Icon,
    Popover,
} from 'antd-mobile';
import http from '../../plugins/axios';
import { dateFormat } from '../../utils/date';

class BlogDetail extends Component {
    constructor(props) {
        super(props);

        this.state = {
            user: JSON.parse(window.sessionStorage.getItem('user')),
            blog: {
                bid: props.match.params.id,
            },
            commentList: [],
            visible: false,
            likedCid: [],
        };
    }

    componentDidMount() {
        this.getBlogDetail();
        this.getCommentList();
        this.getLikedCommentList();
        setTimeout(() => {
            console.log('this.state', this.state);
        }, 2000);
    }

    async getBlogDetail() {
        const res = await http.get(`/blogs/${this.state.blog.bid}`);
        this.setState({ blog: { ...res.data } });
    }

    async getCommentList() {
        const res = await http.get(`/blogs/${this.state.blog.bid}/comments`);
        this.setState({ commentList: res.data });
    }

    async getLikedCommentList() {
        const res = await http.get('/comments/liked');
        this.setState({ likedCid: res.data.likedCid });
    }

    addComment() {
        Modal.prompt('发表评论', `为《${this.state.blog.title}》添加评论`, [
            { text: '取消' },
            {
                text: '提交',
                onPress: async (content) => {
                    let res = await http.post(`/comments`, {
                        bid: this.state.blog.bid,
                        content,
                    });
                    console.log(res);
                    if (res.code !== 201) {
                        Toast.fail(res.message);
                        return;
                    }
                    this.getCommentList();
                },
            },
        ]);
    }

    async changeStar(id) {
        const res = await http.put(`/comments/${id}/star`);
        console.log('res', res);
        this.getCommentList();
        this.getLikedCommentList();
    }

    onSelect = (opt) => {
        this.setState({
            visible: false,
        });
        // 根据点击的按钮，做对应操作
        let action = opt.props.value;
        if (action === 'logout') {
            window.sessionStorage.clear();
            this.props.history.push('/login');
            return;
        }
    };

    handleVisibleChange = (visible) => {
        this.setState({
            visible,
        });
    };

    render() {
        return (
            <div className="blog-edit">
                {/* 顶部导航 */}
                <NavBar
                    icon={<Icon type="left" />}
                    onLeftClick={() => this.props.history.go(-1)}
                    rightContent={
                        <Popover
                            mask
                            visible={this.state.visible}
                            onVisibleChange={this.handleVisibleChange}
                            onSelect={this.onSelect}
                            overlay={[
                                <Popover.Item value="logout">
                                    退出登录
                                </Popover.Item>,
                            ]}
                            align={{
                                overflow: { adjustY: 0, adjustX: 0 },
                                offset: [-10, 0],
                            }}
                        >
                            <div
                                style={{
                                    height: '100%',
                                    padding: '0 15px',
                                    marginRight: '-15px',
                                    display: 'flex',
                                    alignItems: 'center',
                                }}
                            >
                                <Icon type="ellipsis" />
                            </div>
                        </Popover>
                    }
                >
                    博客详情
                </NavBar>

                <WhiteSpace size="lg" />

                {/* 卡片视图 */}
                <Card>
                    <Card.Header
                        title={this.state.blog.title}
                        thumb="https://gw.alipayobjects.com/zos/rmsportal/MRhHctKOineMbKAZslML.jpg"
                        extra={dateFormat(
                            new Date(Date.parse(this.state.blog.create_time)),
                        )}
                    />
                    <Card.Body>
                        <p>{this.state.blog.content}</p>
                    </Card.Body>

                    <WhiteSpace />

                    <Card.Footer
                        content={`评论 ( ${this.state.commentList.length} )`}
                        extra={
                            <Flex
                                justify="end"
                                style={{ cursor: 'pointer' }}
                                onClick={() => this.addComment()}
                            >
                                <i
                                    className="iconfont icondianping"
                                    style={{
                                        fontSize: '18px',
                                        marginRight: '5px',
                                        marginBottom: '2px',
                                    }}
                                ></i>
                                <span>发表评论</span>
                            </Flex>
                        }
                    />
                </Card>
                <WhiteSpace />
                {this.state.commentList.length === 0 ? (
                    <Flex justify="center" align="center">
                        <p>暂无评论</p>
                    </Flex>
                ) : (
                    <List>
                        {this.state.commentList.map((item) => {
                            return (
                                <List.Item
                                    key={item.id}
                                    extra={
                                        <Flex justify="end">
                                            <span
                                                style={{ cursor: 'pointer' }}
                                                onClick={() =>
                                                    this.changeStar(item.id)
                                                }
                                            >
                                                {item.star} 👍{' '}
                                                {this.state.likedCid.includes(
                                                    item.id,
                                                )
                                                    ? '取消点赞'
                                                    : '点赞'}
                                            </span>
                                            <i
                                                className="iconfont icondianzan"
                                                style={{
                                                    fontSize: '20px',
                                                    marginBottom: '2px',
                                                }}
                                            ></i>
                                        </Flex>
                                    }
                                    align="bottom"
                                >
                                    <span>{item.nickname}</span>
                                    <List.Item.Brief>
                                        <p>{item.content}</p>
                                        <p>
                                            {dateFormat(
                                                new Date(item.create_time),
                                            )}
                                        </p>
                                    </List.Item.Brief>
                                </List.Item>
                            );
                        })}
                    </List>
                )}
            </div>
        );
    }
}

export default BlogDetail;
